<?php

namespace app\admin\controller\box;

use app\common\controller\Backend;

/**
 * 货损
 *
 * @icon fa fa-circle-o
 */
class Damage extends Backend {

    /**
     * Damage模型对象
     * @var \app\admin\model\Damage
     */
    protected $model = null;

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\admin\model\Damage;
    }

    /**
     * 查看
     */
    public function index() {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null, null, [], ['createtime' => 'fa_damage.createtime']);
            $admin_info = db('admin')->where('id', $this->auth->id)->find();
            $admin_where = [];

            if ($admin_info['identity'] == 1) {
                if ($admin_info['province'] != 0) {
                    $admin_where['fa_user_box.province'] = $admin_info['province'];
                }
                if ($admin_info['city'] != 0) {
                    $admin_where['fa_user_box.city'] = $admin_info['city'];
                }
                if ($admin_info['area'] != 0) {
                    $admin_where['fa_user_box.area'] = $admin_info['area'];
                }
                if ($admin_info['quarters_id'] != 0) {
                    $admin_where['fa_user_box.quarters_id'] = $admin_info['quarters_id'];
                }
                if ($admin_info['unit_id'] != 0) {
                    $admin_where['fa_user_box.unit_id'] = $admin_info['unit_id'];
                }
                if ($admin_info['room_id'] != 0) {
                    $admin_where['fa_user_box.room_id'] = $admin_info['room_id'];
                }
            } else if ($admin_info['identity'] == 2) {
                $admin_where['fa_user_box.box_no'] = ['in', $admin_info['box_nos']];
            }
            $total = $this->model
                    ->join('fa_user_box', 'fa_damage.user_box_id = fa_user_box.user_box_id', 'left')
                    ->where($where)
                    ->where($admin_where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->field('fa_damage.*,fa_user_box.box_no,fa_user_box.user_box_id,fa_user_box.user_id,fa_user_box.province_name,fa_user_box.city_name,fa_user_box.area_name,fa_user_box.quarters_id,fa_user_box.unit_id,fa_user_box.room_id,fa_user_box.contacts,fa_user_box.telephone')
                    ->join('fa_user_box', 'fa_damage.user_box_id = fa_user_box.user_box_id', 'left')
                    ->where($where)
                    ->where($admin_where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $list = collection($list)->toArray();
            if ($list) {
                foreach ($list as &$val) {
                    $val['sum_amount'] = db('damage')->where(['user_box_id' => $val['user_box_id']])->sum('damage_amount');
                    $val['room_name'] = db('house')->where(['house_id' => $val['room_id']])->value('house_name');
                    $val['unit_name'] = db('house')->where(['house_id' => $val['unit_id']])->value('house_name');
                    $val['quarters_name'] = db('house')->where(['house_id' => $val['quarters_id']])->value('house_name');
                }
                unset($val);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function add() {
        $id = $this->request->param('ids');
        if ($this->request->isPost()) {
            $infos = input('infos/a');
            if ($infos) {
                db()->startTrans();
                try {
                    $damage['user_box_id'] = $id;
                    $damage_amount = 0;
                    $damage_goods = [];
                    foreach ($infos as $key => $val) {
                        $user_box_goods = db('user_box_goods')->where('box_goods_id', $key)->find();

                        //计算货损
                        if ($user_box_goods['stock_num'] > $val['damage_stock_num']) {
                            $diff = $user_box_goods['stock_num'] - $val['damage_stock_num'];
                            $damage_amount += $diff * $user_box_goods['selling_price'];

                            $goods['box_goods_id'] = $key;
                            $goods['selling_price'] = $user_box_goods['selling_price'];
                            $goods['amount'] = $diff * $user_box_goods['selling_price'];
                            $goods['goods_id'] = $user_box_goods['goods_id'];
                            $goods['stock_num'] = $user_box_goods['stock_num'];
                            $goods['damage_stock_num'] = $val['damage_stock_num'];
                            $damage_goods[] = $goods;
                        }
                    }

                    if ($damage_amount > 0) {
                        $damage['damage_amount'] = $damage_amount;
                        $damage['damage_level'] = db('damage_level')->where('amount', '<=', $damage_amount)->order('amount desc')->value('damage_level_name');

                        $damage_id = db('damage')->insertGetId($damage);

                        foreach ($damage_goods as &$val) {
                            $val['damage_id'] = $damage_id;

                            //更新库存
                            $box_goods['updatetime'] = date('Y-m-d H:i:s');
                            $box_goods['stock_num'] = $val['damage_stock_num'];

                            db('user_box_goods')->where('box_goods_id', $val['box_goods_id'])->update($box_goods);

                            unset($val['box_goods_id']);
                        }

                        db('damage_goods')->insertAll($damage_goods);
                    }
                    db()->commit();
                    $this->success();
                } catch (Exception $ex) {
                    db()->rollback();
                    $this->error();
                }
            } else {
                $this->error('没有需要保存的数据');
            }
        } else {
            $user_box_info = db('user_box')->where('user_box_id', $id)->where('status', 1)->find();

            if ($user_box_info) {
                $user_box_info['room_name'] = db('house')->where(['house_id' => $user_box_info['room_id']])->value('house_name');
                $user_box_info['unit_name'] = db('house')->where(['house_id' => $user_box_info['unit_id']])->value('house_name');
                $user_box_info['quarters_name'] = db('house')->where(['house_id' => $user_box_info['quarters_id']])->value('house_name');
                $user_info = db('users')->where('user_id', $user_box_info['user_id'])->find();
                $user_box_info['nick_name'] = $user_info['nick_name'];
                $user_box_info['phone'] = $user_info['phone'];
            }

            $list = db('user_box_goods')
                    ->alias('ubg')
                    ->field('ubg.box_goods_id,ubg.selling_price,ubg.stock_num,ubg.createtime,fa_goods.goods_id,fa_goods.goods_logo,fa_goods.goods_title,fa_goods.goods_model,fa_goods.goods_spec,fa_goods.goods_weight,fa_goods.purchase_price,fa_goods.selling_price as goods_price,fa_goods_brand.brand_title,fa_goods_cate.cate_title')
                    ->join('fa_goods', 'fa_goods.goods_id = fa_user_box_goods.goods_id', 'left')
                    ->join('fa_goods_brand', 'fa_goods_brand.brand_id = fa_goods.brand_id', 'left')
                    ->join('fa_goods_cate', 'fa_goods_cate.cate_id = fa_goods.cate_id', 'left')
                    ->where('ubg.user_box_id', $user_box_info['user_box_id'])
                    ->select();

            $this->assign('list', $list);
            $this->assign('info', $user_box_info);
            $this->assign('ids', $id);
        }
        return $this->view->fetch();
    }

    public function detail() {
        $id = $this->request->param('ids');
        $info = $this->model
                ->field('fa_damage.*,fa_user_box.box_no')
                ->join('fa_user_box', 'fa_damage.user_box_id = fa_user_box.user_box_id', 'left')
                ->where('damage_id', $id)
                ->find();

        $list = db('damage_goods')
                ->alias('dg')
                ->field('dg.*,fa_goods.goods_logo,fa_goods.goods_title,fa_goods.goods_model,fa_goods.goods_spec,fa_goods.goods_weight,fa_goods.purchase_price,fa_goods.selling_price as goods_price,fa_goods_brand.brand_title,fa_goods_cate.cate_title')
                ->join('fa_goods', 'fa_goods.goods_id = dg.goods_id', 'left')
                ->join('fa_goods_brand', 'fa_goods_brand.brand_id = fa_goods.brand_id', 'left')
                ->join('fa_goods_cate', 'fa_goods_cate.cate_id = fa_goods.cate_id', 'left')
                ->where('dg.damage_id', $id)
                ->select();
        
        $this->assign('list', $list);
        $this->assign('info', $info);
        
        return $this->view->fetch();
    }

    public function getBoxByBoxNo() {
        $box_no = input('box_no');

        if (empty($box_no)) {
            $this->error('请填写盒子编号');
        }


        $box_info = db('user_box')->where('box_no', $box_no)->where('status', 1)->find();

        if (empty($box_info)) {
            $this->error('没有找到已布放的盒子');
        }

        $this->success('获取成功', '', $box_info);
    }

}
